package com.lisn.KotlinHtml5

import android.content.Context
import android.util.Log
import android.webkit.JavascriptInterface
import android.webkit.WebView
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.runOnUiThread
import org.jetbrains.anko.toast
import org.json.JSONObject
import java.net.URL

/**
 * Kotlin与H5沟通的桥梁类
 */
class JavaScriptMethods {
    private  val TAG = "JavaScriptMethods"
    private var mWebView: WebView? = null
    private var mContext: Context? = null

    constructor(context: Context?, webview: WebView?) {
        this.mContext = context
        this.mWebView = webview
    }

    @JavascriptInterface // android4.2以后，不加上这个注解，H5不能调用kotlin方法
    fun showToast(json: String) {
        // Toast.makeText(mContext, json, Toast.LENGTH_SHORT).show()
        // mContext?.toast(json)
        Log.e(TAG, "showToast: json "+json, )
        mContext?.let { it.toast(json) }
    }

    @JavascriptInterface
    fun getHotelData(json: String) {
        var jsJson = JSONObject(json)
        val callback = jsJson.optString("callback")
        println("获取酒店数据 "+callback)
        // 异步操作，子线程请求服务器
        doAsync {
            // var url = URL("http://127.0.0.1:8080/hotel.json")
            // val result = url.readText()
            // println("获取酒店数据=" + result)
            //callback步骤2：回传数据个h5
            //调用js方法必须在主线程
            var result = "{\"name\":\"aaaa\"}";
            callbackJavaScript(callback, result)
        }
    }

    /**
     * 统一管理所有kotlin回调js方法
     */
    private fun callbackJavaScript(callback: String, result: String) {
        mContext?.let {
            it.runOnUiThread {
                // mWebView?.loadUrl("javascript:receiveHotlData("+result+")")
                mWebView?.let {
                    it.loadUrl("javascript:" + callback + "(" + result + ")")
                }
            }
        }
    }


}